// lib/taskdata.ts
// 数据管理相关的 API 接口

import { apiClient, API_ENDPOINTS, TokenManager } from '@/lib/api-client'
import type { 
  DataRecord, 
  CreateDataRequest, 
  UpdateDataRequest, 
  DataResponse, 
  DataListResponse,
  DataFilters,
  FileUploadResponse,
  DataErrorResponse
} from '@/types/taskdata'

/**
 * 数据转换工具类
 */
export class DataTransformer {
  /**
   * 将表单数据转换为 API 请求格式
   */
  static formToRequest(formData: {
    name: string
    description: string
    type: string
    location: string
    collection_date: string
    crop_type?: string
    attachments?: File[]
  }): CreateDataRequest | UpdateDataRequest {
    return {
      project_id: '', // 需要在调用时设置
      name: formData.name,
      description: formData.description,
      type: formData.type as any,
      location: formData.location,
      collection_date: formData.collection_date,
      crop_type: formData.crop_type,
      attachments: formData.attachments || []
    }
  }

  /**
   * 为包含附件的请求创建 FormData
   */
  static createFormData(data: CreateDataRequest | UpdateDataRequest): FormData {
    const formData = new FormData()
    
    // 添加数据基本信息
    Object.entries(data).forEach(([key, value]) => {
      if (key !== 'attachments' && value !== undefined) {
        formData.append(key, value.toString())
      }
    })
    
    // 添加附件
    if (data.attachments && data.attachments.length > 0) {
      data.attachments.forEach((file) => {
        formData.append('attachments', file)
      })
    }
    
    return formData
  }
}

/**
 * 数据管理 API 类
 */
export class DataAPI {
  
  /**
   * 获取数据记录列表
   */
  static async getDataRecords(filters?: DataFilters): Promise<DataListResponse> {
    const queryParams = new URLSearchParams()
    
    if (filters?.project_id) {
      queryParams.append('project_id', filters.project_id)
    }
    if (filters?.type) {
      queryParams.append('type', filters.type)
    }
    if (filters?.owner) {
      queryParams.append('owner', filters.owner)
    }
    if (filters?.crop_type) {
      queryParams.append('crop_type', filters.crop_type)
    }
    if (filters?.location) {
      queryParams.append('location', filters.location)
    }
    if (filters?.search) {
      queryParams.append('search', filters.search)
    }
    if (filters?.date_range) {
      queryParams.append('start_date', filters.date_range.start)
      queryParams.append('end_date', filters.date_range.end)
    }
    
    const endpoint = `/api/data/${queryParams.toString() ? `?${queryParams.toString()}` : ''}`
    return apiClient.get<DataListResponse>(endpoint)
  }

  /**
   * 根据 ID 获取数据记录详情
   */
  static async getDataRecord(dataId: string): Promise<DataRecord> {
    return apiClient.get<DataRecord>(`/api/data/${dataId}/`)
  }

  /**
   * 创建新数据记录
   */
  static async createDataRecord(dataRequest: CreateDataRequest): Promise<DataResponse> {
    // 处理附件上传
    if (dataRequest.attachments && dataRequest.attachments.length > 0) {
      const formData = DataTransformer.createFormData(dataRequest)
      return apiClient.post<DataResponse>('/api/data/', formData)
    } else {
      // 不包含附件的数据记录
      const payload = { ...dataRequest }
      delete payload.attachments
      return apiClient.post<DataResponse>('/api/data/', payload)
    }
  }

  /**
   * 更新数据记录
   */
  static async updateDataRecord(
    dataId: string, 
    dataRequest: UpdateDataRequest
  ): Promise<DataResponse> {
    // 处理附件上传
    if (dataRequest.attachments && dataRequest.attachments.length > 0) {
      const formData = DataTransformer.createFormData(dataRequest)
      return apiClient.patch<DataResponse>(`/api/data/${dataId}/`, formData)
    } else {
      // 确保所有数据都经过正确转换
      const payload = { ...dataRequest }
      // 移除 attachments 字段避免发送空数组
      delete payload.attachments
      return apiClient.patch<DataResponse>(`/api/data/${dataId}/`, payload)
    }
  }

  /**
   * 删除数据记录
   */
  static async deleteDataRecord(dataId: string): Promise<void> {
    return apiClient.delete<void>(`/api/data/${dataId}/`)
  }

  /**
   * 上传数据附件
   */
  static async uploadDataFiles(
    dataId: string, 
    files: File[]
  ): Promise<FileUploadResponse> {
    const formData = new FormData()
    
    files.forEach((file) => {
      formData.append('files', file)
    })
    
    return apiClient.post<FileUploadResponse>(
      `/api/data/${dataId}/files/`, 
      formData
    )
  }

  /**
   * 删除数据附件
   */
  static async deleteDataFile(
    dataId: string, 
    fileId: string
  ): Promise<void> {
    return apiClient.delete<void>(`/api/data/${dataId}/files/${fileId}/`)
  }

  /**
   * 下载数据附件
   */
  static async downloadDataFile(
    dataId: string, 
    fileId: string,
    fileName: string
  ): Promise<void> {
    try {
      const token = TokenManager.getAccessToken()
      // 直接构造 URL
      const baseUrl = process.env.NODE_ENV === 'production' ? '' : 'http://localhost:8000'
      const url = `${baseUrl}/api/data/${dataId}/files/${fileId}/download/`
      
      const response = await fetch(url, {
        method: 'GET',
        headers: {
          'Authorization': `Bearer ${token}`
        }
      })
      
      if (!response.ok) {
        throw new Error('下载失败')
      }
      
      const blob = await response.blob()
      const downloadUrl = window.URL.createObjectURL(blob)
      
      // 创建下载链接
      const link = document.createElement('a')
      link.href = downloadUrl
      link.download = fileName
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      
      // 清理 URL 对象
      window.URL.revokeObjectURL(downloadUrl)
    } catch (error: any) {
      console.error('下载附件失败:', error)
      throw error
    }
  }

  /**
   * 获取项目的数据统计
   */
  static async getProjectDataStats(projectId: string): Promise<{
    total: number
    by_type: Record<string, number>
    storage_size: number
  }> {
    return apiClient.get(`/api/data/stats/project/${projectId}/`)
  }

  /**
   * 批量删除数据记录
   */
  static async batchDeleteDataRecords(dataIds: string[]): Promise<void> {
    return apiClient.post('/api/data/batch-delete/', { ids: dataIds })
  }
}

export default DataAPI